const express = require('express');
const upload = require('multer')({ dest: 'uploads/' });
const path = require('path');
const fs = require('fs');

let OSS = require('ali-oss');

const port = 3000;

let client = new OSS({
  endpoint: 'oss-cn-shenzhen.aliyuncs.com',
  accessKeyId: 'xxxx',
  accessKeySecret: 'xxxxx',
  bucket:'xxxx-kaki'
});

let  app = express();

app.set('port', port);
app.use(express.static(path.join(__dirname, 'uploads/')));

//处理跨域请求
app.all('*',function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.post('/upload', upload.single('img'), (req, res) => {
  // 没有附带文件
  if (!req.file) {
    res.json({ ok: false });
    return;
  }
     
  // 输出文件信息
 
  console.log('====================================================');
  console.log('fieldname: ' + req.file.fieldname);
  console.log('originalname: ' + req.file.originalname);
  console.log('encoding: ' + req.file.encoding);
  console.log('mimetype: ' + req.file.mimetype);
  console.log('size: ' + (req.file.size / 1024).toFixed(2) + 'KB');
  console.log('destination: ' + req.file.destination);
  console.log('filename: ' + req.file.filename);
  console.log('path: ' + req.file.path);
    
  putStream(req.file.path,req.file.originalname,res);
  
});

async function putStream (path,originalname,res) {
  try {
	  // use 'chunked encoding'
	  let stream = fs.createReadStream(path);
	  let result = await client.putStream(originalname, stream);
	  console.log(result);
	  
	  res.json({ ok: true ,info: result.url});
	  
  } catch (e) {
    console.log(e)
  }
}



app.listen(port, () => {
  console.log("[Server] localhost:" + port);
});
